/*
 *  Copyright 2008 Danny Lagrouw
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package org.bastion.service.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.bastion.domain.Alert;
import org.bastion.service.AlertService;

/**
 * An alert service that translates alert codes into messages using
 * a resource bundle.
 * 
 * @author Danny
 */
public class ResourceBundleAlertService implements AlertService {

    List<Alert> alerts = new ArrayList<Alert>();

    private ResourceBundle resourceBundle;

    public ResourceBundleAlertService(String resourceBundleName) {
    	setResourceBundle(resourceBundleName);
    }
    
    private void setResourceBundle(String resourceBundleName) {
		resourceBundle = ResourceBundle.getBundle(resourceBundleName);
	}

    public void addAlert(Alert alert) {
        alerts.add(alert);
    }

    public List<Alert> getAlerts(boolean clearAlertsAfterwards) {
    	List<Alert> translatedAlerts = getTranslatedAlerts(alerts);
        if (clearAlertsAfterwards) {
            alerts.clear();
        }
        return translatedAlerts;
    }

	protected List<Alert> getTranslatedAlerts(List<Alert> alerts) {
		List<Alert> translatedAlerts = new ArrayList<Alert>(alerts.size());
		for (Alert alert : alerts) {
			translatedAlerts.add(getTranslatedAlert(alert));
		}
		return translatedAlerts;
	}

	protected Alert getTranslatedAlert(Alert alert) {
		String code = alert.getCode();
		if (resourceBundle.containsKey(code)) {
			String message = resourceBundle.getString(code);
			message = MessageFormat.format(message, (Object[]) alert.getArgs());
			return new Alert(message, alert.getLevel());
		} else {
			return new Alert("??" + code + "??", alert.getLevel(), alert.getArgs());
		}
	}

}
